import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

import express from 'express';

// ---- 初始化基础配置 ----
// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 创建Express应用
const app = express();
const PORT = 3000;

// 中间件配置
app.use(express.json()); // 解析JSON请求体

// 日志中间件
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// CORS中间件
app.use((req, res, next) => {
  // 允许的来源列表
  const allowedOrigins = ['http://localhost:3000', 'http://localhost:5799'];
  const origin = req.headers.origin;

  if (allowedOrigins.includes(origin)) {
    res.header('Access-Control-Allow-Origin', origin);
  }

  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.header('Access-Control-Allow-Credentials', 'true');

  if (req.method === 'OPTIONS') {
    return res.sendStatus(200);
  }

  next();
});

// ---- 数据库初始化 ----
const db = {};
const dataDir = path.join(__dirname, 'dbs');

// 确保dbs目录存在
if (!fs.existsSync(dataDir)) {
  fs.mkdirSync(dataDir, { recursive: true });
}

// 读取 dbs 目录下的所有 .json 文件
fs.readdirSync(dataDir).forEach(file => {
  if (path.extname(file) === '.json') {
    const fileName = path.basename(file, '.json');
    const filePath = path.join(dataDir, file);
    const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
    db[fileName] = data;
  }
});

// 确保必要的集合存在且为数组类型
const ensureCollectionsExist = () => {
  // 动态获取 src/server/dbs 目录下的所有 JSON 文件，作为必要的集合
  const files = fs.readdirSync(dataDir);
  const requiredCollections = files
    .filter(file => file.endsWith('.json'))
    .map(file => file.replace('.json', ''));

  requiredCollections.forEach(collection => {
    if (!Array.isArray(db[collection])) {
      db[collection] = [];
    }
  });
};

ensureCollectionsExist();

// ---- 索引管理 ----
const indexes = {};

// 为每个集合创建基本索引结构
Object.keys(db).forEach(collection => {
  indexes[collection] = {
    id: new Map() // 所有集合都应该有id索引
  };

  // 为特定集合添加额外索引
  if (collection === 'permissions' || collection === 'roles') {
    indexes[collection].name = new Map();
  } else if (collection === 'users') {
    indexes[collection].username = new Map();
    indexes[collection].email = new Map();
  }
});

// 初始化索引
const initializeIndexes = () => {
  // 为每个集合初始化索引
  Object.keys(db).forEach(collection => {
    db[collection].forEach(item => {
      // 初始化id索引
      if (item.id) {
        indexes[collection].id.set(String(item.id), item);
      }

      // 初始化特定集合的额外索引
      if (indexes[collection].name && item.name) {
        indexes[collection].name.set(item.name.toLowerCase(), item);
      }
      if (indexes[collection].username && item.username) {
        indexes[collection].username.set(item.username.toLowerCase(), item);
      }
      if (indexes[collection].email && item.email) {
        indexes[collection].email.set(item.email.toLowerCase(), item);
      }
    });
  });
};

initializeIndexes();

// ---- 工具函数 ----
// 找出当前列表中最大的id
const getMaxId = (tableName) => {
  if (db[tableName].length === 0) {
    return 0;
  }
  return Math.max(...db[tableName].map(item => Number(item.id)));
};

// 当前最大id
let currentMaxPermissionId = getMaxId('permissions');
let currentMaxUserId = getMaxId('users');
let currentMaxRoleId = getMaxId('roles');

// 保存数据库的防抖计时器
let saveDbTimer = null;

// 防抖保存时间（毫秒）
const DEBOUNCE_SAVE_TIME = 1000;

// 更新索引
const updateIndex = (collection, item, operation) => {
  const collectionIndexes = indexes[collection];
  const itemId = String(item.id);

  switch (collection) {
    case 'permissions':
      if (operation === 'add' || operation === 'update') {
        collectionIndexes.id.set(itemId, item);
        if (item.name) {
          collectionIndexes.name.set(item.name.toLowerCase(), item);
        }
      } else if (operation === 'delete') {
        collectionIndexes.id.delete(itemId);
        if (item.name) {
          collectionIndexes.name.delete(item.name.toLowerCase());
        }
      }
      break;

    case 'users':
      if (operation === 'add' || operation === 'update') {
        collectionIndexes.id.set(itemId, item);
        if (item.username) {
          collectionIndexes.username.set(item.username.toLowerCase(), item);
        }
        if (item.email) {
          collectionIndexes.email.set(item.email.toLowerCase(), item);
        }
      } else if (operation === 'delete') {
        collectionIndexes.id.delete(itemId);
        if (item.username) {
          collectionIndexes.username.delete(item.username.toLowerCase());
        }
        if (item.email) {
          collectionIndexes.email.delete(item.email.toLowerCase());
        }
      }
      break;

    case 'roles':
      if (operation === 'add' || operation === 'update') {
        collectionIndexes.id.set(itemId, item);
        if (item.name) {
          collectionIndexes.name.set(item.name.toLowerCase(), item);
        }
      } else if (operation === 'delete') {
        collectionIndexes.id.delete(itemId);
        if (item.name) {
          collectionIndexes.name.delete(item.name.toLowerCase());
        }
      }
      break;
  }
};

// 防抖保存数据库到文件
const saveDb = () => {
  // 清除之前的计时器
  if (saveDbTimer) {
    clearTimeout(saveDbTimer);
  }

  // 设置新的计时器
  saveDbTimer = setTimeout(() => {
    try {
      // 分别保存每个集合到对应的文件
      Object.keys(db).forEach(collection => {
        const filePath = path.join(dataDir, `${collection}.json`);
        fs.writeFileSync(filePath, JSON.stringify(db[collection], null, 2), 'utf8');
      });

      console.log('数据库已保存到文件');
    } catch (error) {
      console.error('保存数据库失败:', error);
    }
  }, DEBOUNCE_SAVE_TIME);
};

// 密码哈希函数
const hashPassword = (password) => {
  const salt = crypto.randomBytes(16).toString('hex');
  const hash = crypto.pbkdf2Sync(password, salt, 1000, 64, 'sha512').toString('hex');
  return { salt, hash };
};

// 密码验证函数
const verifyPassword = (password, salt, hash) => {
  if (!salt || !hash) {
    return false;
  }
  const newHash = crypto.pbkdf2Sync(password, salt, 1000, 64, 'sha512').toString('hex');
  return newHash === hash;
};

// ---- API路由定义 ----
// 输入验证工具函数
function validateInput(data, rules) {
  const errors = [];

  for (const field in rules) {
    const rule = rules[field];
    const value = data[field];

    // 必填字段检查
    if (rule.required && (value === undefined || value === null || value === '')) {
      errors.push(`${field} 是必填字段`);
      continue;
    }

    // 如果字段可选且未提供，跳过后续验证
    if (!rule.required && value === undefined) {
      continue;
    }

    // 数据类型检查
    if (rule.type && typeof value !== rule.type) {
      errors.push(`${field} 必须是 ${rule.type} 类型`);
    }

    // 字符串长度检查
    if (typeof value === 'string') {
      if (rule.minLength && value.length < rule.minLength) {
        errors.push(`${field} 长度不能少于 ${rule.minLength} 个字符`);
      }
      if (rule.maxLength && value.length > rule.maxLength) {
        errors.push(`${field} 长度不能超过 ${rule.maxLength} 个字符`);
      }
    }

    // 自定义验证函数
    if (rule.validate && typeof rule.validate === 'function') {
      const result = rule.validate(value, data);
      if (result !== true) {
        errors.push(result);
      }
    }
  }

  return errors.length ? errors : null;
}

// 路由实例创建
const authRouter = express.Router();
const permissionRouter = express.Router();
const userRouter = express.Router();
const roleRouter = express.Router();

// ---- 认证相关路由 ----
authRouter.post('/login', (req, res) => {
  const { account, password } = req.body;

  // 输入验证
  const errors = validateInput(req.body, {
    account: {
      required: true,
      type: 'string',
      minLength: 3,
      maxLength: 50
    },
    password: {
      required: true,
      type: 'string',
      minLength: 6,
      maxLength: 20
    }
  });

  if (errors) {
    return res.status(400).json({ message: '输入验证失败', errors });
  }

  // 查找用户
  const user = db.users.find(u =>
    (u.username === account || u.email === account) &&
    u.status === 'active'
  );

  if (!user) {
    return res.status(401).json({ message: '账号或密码错误' });
  }

  // 验证密码
  if (!verifyPassword(password, user.salt, user.password)) {
    return res.status(401).json({ message: '账号或密码错误' });
  }

  // 生成token（简化版，实际项目中应该使用JWT等更安全的方式）
  const token = `${user.id}-token-${Date.now()}`;

  // 获取用户角色
  const userRole = user.role || 'user';

  // 获取角色对应的权限
  const role = db.roles.find(r => r.name === userRole && r.status === 'active');
  // 将权限ID转换为数字类型
  const permissions = role ? role.permissions.map(p => parseInt(p)) : [];

  // 返回用户信息、角色和权限
  res.json({
    token: token,
    user: {
      id: user.id,
      name: user.name,
      username: user.username,
      email: user.email,
      avatar: user.avatar || '',
      role: userRole,
      permissions: permissions,
      createdAt: user.createdAt,
      updatedAt: user.updatedAt
    }
  });
});

authRouter.post('/logout', (req, res) => {
  res.json({ message: '退出成功' });
});

authRouter.get('/current-user', (req, res) => {
  // 从请求头获取token
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: '未授权' });
  }

  // 解析token，格式为 ${user.id}-token-${timestamp}
  const tokenParts = token.split('-');
  if (tokenParts.length !== 3 || tokenParts[1] !== 'token') {
    return res.status(401).json({ message: '无效的token格式' });
  }

  const userId = tokenParts[0];

  // 从数据库中查找用户
  const user = db.users.find(u => u.id === userId && u.status === 'active');

  if (!user) {
    return res.status(401).json({ message: '用户不存在或已停用' });
  }

  // 获取用户角色
  const userRole = user.role || 'user';

  // 获取角色对应的权限
  const role = db.roles.find(r => r.name === userRole && r.status === 'active');
  const permissions = role ? role.permissions : [];

  // 返回用户信息、角色和权限
  res.json({
    id: user.id,
    name: user.name || user.username,
    avatar: user.avatar || '',
    role: userRole,
    permissions: permissions,
    username: user.username,
    email: user.email,
    createdAt: user.createdAt,
    updatedAt: user.updatedAt
  });
});

// ---- 权限相关路由 ----
permissionRouter.get('/', (req, res) => {
  res.json(db.permissions);
});

permissionRouter.get('/:id', (req, res) => {
  const permission = indexes.permissions.id.get(req.params.id);
  if (permission) {
    res.json(permission);
  } else {
    res.status(404).json({ message: '权限不存在' });
  }
});

permissionRouter.post('/', (req, res) => {
  // 输入验证
  const errors = validateInput(req.body, {
    name: {
      required: true,
      type: 'string',
      minLength: 1,
      maxLength: 50
    },
    code: {
      required: true,
      type: 'string',
      minLength: 1,
      maxLength: 100
    },
    pid: {
      required: true,
      type: 'number'
    },
    level: {
      required: true,
      type: 'number'
    },
    sort: {
      required: true,
      type: 'number'
    },
    isLeaf: {
      required: true,
      type: 'boolean'
    },
    icon: {
      required: false,
      type: 'string'
    },
    path: {
      required: false,
      type: 'string'
    },
    component: {
      required: false,
      type: 'string'
    },
    status: {
      required: true,
      type: 'number',
      validate: (value) => {
        // 检查状态是否有效（0或1）
        return [0, 1].includes(value) ? true : '状态必须是 0 或 1';
      }
    }
  });

  if (errors) {
    return res.status(400).json({ message: '输入验证失败', errors });
  }

  // 生成自增id
  currentMaxPermissionId++;
  const newPermission = {
    id: currentMaxPermissionId,
    ...req.body,
  };

  // 添加新权限到数据库
  db.permissions.push(newPermission);

  // 更新索引
  updateIndex('permissions', newPermission, 'add');

  // 如果有父权限，更新父权限的isLeaf属性
  if (newPermission.pid) {
    const parentPermission = indexes.permissions.id.get(String(newPermission.pid));
    if (parentPermission) {
      parentPermission.isLeaf = false;
      updateIndex('permissions', parentPermission, 'update');
      console.log(`父权限ID: ${newPermission.pid} 的isLeaf属性已更新为false`);
    }
  }

  // 保存数据库
  saveDb();

  // 返回新创建的权限
  res.status(201).json(newPermission);
});

permissionRouter.put('/:id', (req, res) => {
  const permissionId = req.params.id;
  const permissionIndex = db.permissions.findIndex(p => String(p.id) === String(permissionId));

  if (permissionIndex !== -1) {
    const oldPermission = db.permissions[permissionIndex];
    const updatedPermission = {
      ...oldPermission,
      ...req.body,
    };

    // 检查父权限是否变化
    if (oldPermission.pid !== updatedPermission.pid) {
      // 更新旧父权限的isLeaf属性
      if (oldPermission.pid) {
        const oldParentPermission = indexes.permissions.id.get(String(oldPermission.pid));
        if (oldParentPermission) {
          const hasChildren = db.permissions.some(p => String(p.pid) === String(oldParentPermission.id) && String(p.id) !== String(permissionId));
          oldParentPermission.isLeaf = !hasChildren;
          updateIndex('permissions', oldParentPermission, 'update');
          console.log(`旧父权限ID: ${oldPermission.pid} 的isLeaf属性已更新为${!hasChildren}`);
        }
      }

      // 更新新父权限的isLeaf属性
      if (updatedPermission.pid) {
        const newParentPermission = indexes.permissions.id.get(String(updatedPermission.pid));
        if (newParentPermission) {
          newParentPermission.isLeaf = false;
          updateIndex('permissions', newParentPermission, 'update');
          console.log(`新父权限ID: ${updatedPermission.pid} 的isLeaf属性已更新为false`);
        }
      }
    }

    // 更新数据库和索引
    db.permissions[permissionIndex] = updatedPermission;
    updateIndex('permissions', updatedPermission, 'update');
    saveDb();

    res.json(updatedPermission);
  } else {
    res.status(404).json({ message: '权限不存在' });
  }
});

permissionRouter.delete('/batch', (req, res) => {
  const { ids } = req.body;
  if (!ids || !Array.isArray(ids)) {
    return res.status(400).json({ message: '请提供有效的权限ID列表' });
  }

  try {
    // 批量删除权限
    const deletedPermissions = [];
    for (const id of ids) {
      const permissionIndex = db.permissions.findIndex(p => String(p.id) === String(id));
      if (permissionIndex !== -1) {
        const deletedPermission = db.permissions[permissionIndex];
        deletedPermissions.push(deletedPermission);

        // 删除权限
        db.permissions.splice(permissionIndex, 1);
        updateIndex('permissions', deletedPermission, 'delete');

        // 检查父权限是否还有子权限，如果没有，更新其isLeaf属性为true
        if (deletedPermission.pid) {
          const parentPermission = indexes.permissions.id.get(String(deletedPermission.pid));
          if (parentPermission) {
            const hasChildren = db.permissions.some(p => String(p.pid) === String(parentPermission.id));
            if (!hasChildren) {
              parentPermission.isLeaf = true;
              updateIndex('permissions', parentPermission, 'update');
              console.log(`父权限ID: ${parentPermission.id} 的isLeaf属性已更新为true`);
            }
          }
        }
      }
    }

    // 保存数据库
    saveDb();

    res.json(deletedPermissions);
  } catch (error) {
    console.error('批量删除权限失败:', error);
    res.status(500).json({ message: '批量删除权限失败' });
  }
});

permissionRouter.delete('/:id', (req, res) => {
  const permissionId = req.params.id;
  const permissionIndex = db.permissions.findIndex(p => String(p.id) === String(permissionId));

  if (permissionIndex !== -1) {
    const deletedPermission = db.permissions[permissionIndex];

    // 删除权限
    db.permissions.splice(permissionIndex, 1);
    updateIndex('permissions', deletedPermission, 'delete');

    // 检查父权限是否还有子权限，如果没有，更新其isLeaf属性为true
    if (deletedPermission.pid) {
      const parentPermission = indexes.permissions.id.get(String(deletedPermission.pid));
      if (parentPermission) {
        const hasChildren = db.permissions.some(p => String(p.pid) === String(parentPermission.id));
        if (!hasChildren) {
          parentPermission.isLeaf = true;
          updateIndex('permissions', parentPermission, 'update');
          console.log(`父权限ID: ${parentPermission.id} 的isLeaf属性已更新为true`);
        }
      }
    }

    saveDb();
    res.json(deletedPermission);
  } else {
    res.status(404).json({ message: '权限不存在' });
  }
});

// ---- 用户相关路由 ----
userRouter.get('/', (req, res) => {
  let users = [...db.users];
  const { page = 1, pageSize = 10, keyword, role, status, sortBy, sortOrder = 'asc' } = req.query;

  // 筛选 - 使用索引优化关键词搜索
  if (keyword) {
    const searchKeyword = keyword.toLowerCase();
    const keywordUsers = new Set();

    // 检查用户名索引
    for (const [username, user] of indexes.users.username) {
      if (username.includes(searchKeyword)) {
        keywordUsers.add(user);
      }
    }

    // 检查邮箱索引
    for (const [email, user] of indexes.users.email) {
      if (email.includes(searchKeyword)) {
        keywordUsers.add(user);
      }
    }

    users = Array.from(keywordUsers);
  }

  if (role) {
    users = users.filter(user => user.role === role);
  }
  if (status) {
    users = users.filter(user => user.status === status);
  }

  // 排序
  if (sortBy && users.length > 0) {
    users.sort((a, b) => {
      const aVal = a[sortBy];
      const bVal = b[sortBy];
      if (typeof aVal === 'string') {
        return sortOrder === 'asc'
          ? aVal.localeCompare(bVal)
          : bVal.localeCompare(aVal);
      } else {
        return sortOrder === 'asc'
          ? aVal - bVal
          : bVal - aVal;
      }
    });
  }

  // 分页
  const total = users.length;
  const start = (page - 1) * pageSize;
  const end = start + parseInt(pageSize);
  const paginatedUsers = users.slice(start, end);

  res.json({ list: paginatedUsers, total });
});

userRouter.get('/:id', (req, res) => {
  const user = indexes.users.id.get(req.params.id);
  if (user) {
    res.json(user);
  } else {
    res.status(404).json({ message: '用户不存在' });
  }
});

userRouter.post('/', (req, res) => {
  // 输入验证
  const errors = validateInput(req.body, {
    username: {
      required: true,
      type: 'string',
      minLength: 3,
      maxLength: 20,
      validate: (value) => {
        // 检查用户名是否已存在
        const existingUser = indexes.users.username.get(value.toLowerCase());
        return existingUser ? '用户名已存在' : true;
      }
    },
    email: {
      required: true,
      type: 'string',
      validate: (value) => {
        // 检查邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(value)) {
          return '邮箱格式不正确';
        }
        // 检查邮箱是否已存在
        const existingUser = indexes.users.email.get(value.toLowerCase());
        return existingUser ? '邮箱已存在' : true;
      }
    },
    password: {
      required: true,
      type: 'string',
      minLength: 6,
      maxLength: 20
    },
    role: {
      required: true,
      type: 'string',
      validate: (value) => {
        // 检查角色是否有效
        const validRoles = ['admin', 'user', 'tenant'];
        return validRoles.includes(value) ? true : `角色必须是 ${validRoles.join(', ')} 中的一个`;
      }
    },
    status: {
      required: true,
      type: 'string',
      validate: (value) => {
        // 检查状态是否有效
        const validStatuses = ['active', 'inactive'];
        return validStatuses.includes(value) ? true : `状态必须是 ${validStatuses.join(', ')} 中的一个`;
      }
    }
  });

  if (errors) {
    return res.status(400).json({ message: '输入验证失败', errors });
  }

  // 生成自增id
  currentMaxUserId++;
  const now = new Date().toISOString();

  // 处理密码哈希
  const userData = { ...req.body };
  if (userData.password) {
    const { salt, hash } = hashPassword(userData.password);
    userData.salt = salt;
    userData.password = hash; // 存储哈希后的密码，而不是明文
  }

  const newUser = {
    id: currentMaxUserId.toString(),
    createdAt: now,
    updatedAt: now,
    ...userData,
  };

  // 添加新用户到数据库
  db.users.push(newUser);
  updateIndex('users', newUser, 'add');
  saveDb();

  // 返回新创建的用户
  res.status(201).json(newUser);
});

userRouter.put('/:id', (req, res) => {
  const userId = req.params.id;
  const userIndex = db.users.findIndex(u => u.id === userId);

  if (userIndex === -1) {
    return res.status(404).json({ message: '用户不存在' });
  }

  const oldUser = db.users[userIndex];

  // 输入验证
  const errors = validateInput(req.body, {
    username: {
      required: false,
      type: 'string',
      minLength: 3,
      maxLength: 20,
      validate: (value) => {
        // 检查用户名是否已存在（排除当前用户）
        const existingUser = indexes.users.username.get(value.toLowerCase());
        return existingUser && existingUser.id !== userId ? '用户名已存在' : true;
      }
    },
    email: {
      required: false,
      type: 'string',
      validate: (value) => {
        if (!value) return true;
        // 检查邮箱格式
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(value)) {
          return '邮箱格式不正确';
        }
        // 检查邮箱是否已存在（排除当前用户）
        const existingUser = indexes.users.email.get(value.toLowerCase());
        return existingUser && existingUser.id !== userId ? '邮箱已存在' : true;
      }
    },
    password: {
      required: false,
      type: 'string',
      minLength: 6,
      maxLength: 20
    },
    role: {
      required: false,
      type: 'string',
      validate: (value) => {
        if (!value) return true;
        // 检查角色是否有效
        const validRoles = ['admin', 'user', 'tenant'];
        return validRoles.includes(value) ? true : `角色必须是 ${validRoles.join(', ')} 中的一个`;
      }
    },
    status: {
      required: false,
      type: 'string',
      validate: (value) => {
        if (!value) return true;
        // 检查状态是否有效
        const validStatuses = ['active', 'inactive'];
        return validStatuses.includes(value) ? true : `状态必须是 ${validStatuses.join(', ')} 中的一个`;
      }
    }
  });

  if (errors) {
    return res.status(400).json({ message: '输入验证失败', errors });
  }

  // 处理密码哈希（如果有更新密码）
  const updateData = { ...req.body };
  if (updateData.password) {
    const { salt, hash } = hashPassword(updateData.password);
    updateData.salt = salt;
    updateData.password = hash; // 存储哈希后的密码，而不是明文
  }

  const updatedUser = {
    ...oldUser,
    ...updateData,
    updatedAt: new Date().toISOString(),
  };

  // 更新数据库和索引
  db.users[userIndex] = updatedUser;
  updateIndex('users', updatedUser, 'update');
  saveDb();

  res.json(updatedUser);
});

userRouter.delete('/batch', (req, res) => {
  const { ids } = req.body;
  if (!ids || !Array.isArray(ids)) {
    return res.status(400).json({ message: '请提供有效的用户ID列表' });
  }

  try {
    // 批量删除用户
    const deletedUsers = [];
    for (const id of ids) {
      const userIndex = db.users.findIndex(u => u.id === id);
      if (userIndex !== -1) {
        const deletedUser = db.users[userIndex];
        deletedUsers.push(deletedUser);

        db.users.splice(userIndex, 1);
        updateIndex('users', deletedUser, 'delete');
      }
    }

    // 保存数据库
    saveDb();

    res.json(deletedUsers);
  } catch (error) {
    console.error('批量删除用户失败:', error);
    res.status(500).json({ message: '批量删除用户失败' });
  }
});

userRouter.delete('/:id', (req, res) => {
  const userId = req.params.id;
  const userIndex = db.users.findIndex(u => u.id === userId);

  if (userIndex !== -1) {
    const deletedUser = db.users[userIndex];
    db.users.splice(userIndex, 1);
    updateIndex('users', deletedUser, 'delete');
    saveDb();
    res.json(deletedUser);
  } else {
    res.status(404).json({ message: '用户不存在' });
  }
});

userRouter.post('/:id/reset-password', (req, res) => {
  const userId = req.params.id;
  const userIndex = db.users.findIndex(u => u.id === userId);

  if (userIndex !== -1) {
    const oldUser = db.users[userIndex];
    const updatedUser = {
      ...oldUser,
      updatedAt: new Date().toISOString(),
    };

    // 如果提供了新密码，则更新密码（使用哈希）
    if (req.body.newPassword) {
      const { salt, hash } = hashPassword(req.body.newPassword);
      updatedUser.salt = salt;
      updatedUser.password = hash; // 存储哈希后的密码，而不是明文
    }

    // 更新数据库和索引
    db.users[userIndex] = updatedUser;
    updateIndex('users', updatedUser, 'update');
    saveDb();

    res.json({ message: '密码重置成功' });
  } else {
    res.status(404).json({ message: '用户不存在' });
  }
});

// ---- 角色相关路由 ----
roleRouter.get('/', (req, res) => {
  let roles = [...db.roles];
  const { page = 1, pageSize = 10, keyword } = req.query;

  // 筛选 - 使用索引优化关键词搜索
  if (keyword) {
    const searchKeyword = keyword.toLowerCase();
    const keywordRoles = new Set();

    // 检查角色名索引
    for (const [name, role] of indexes.roles.name) {
      if (name.includes(searchKeyword)) {
        keywordRoles.add(role);
      }
    }

    // 检查描述
    for (const role of db.roles) {
      if (role.description && role.description.toLowerCase().includes(searchKeyword)) {
        keywordRoles.add(role);
      }
    }

    roles = Array.from(keywordRoles);
  }

  // 分页
  const total = roles.length;
  const start = (page - 1) * pageSize;
  const end = start + parseInt(pageSize);
  const paginatedRoles = roles.slice(start, end);

  res.json({ list: paginatedRoles, total });
});

roleRouter.get('/:id', (req, res) => {
  const role = indexes.roles.id.get(req.params.id);
  if (role) {
    res.json(role);
  } else {
    res.status(404).json({ message: '角色不存在' });
  }
});

roleRouter.post('/', (req, res) => {
  // 输入验证
  const errors = validateInput(req.body, {
    name: {
      required: true,
      type: 'string',
      minLength: 1,
      maxLength: 50
    },
    code: {
      required: true,
      type: 'string',
      minLength: 1,
      maxLength: 100
    },
    status: {
      required: true,
      type: 'string',
      validate: (value) => {
        // 检查状态是否有效
        const validStatuses = ['active', 'inactive'];
        return validStatuses.includes(value) ? true : `状态必须是 ${validStatuses.join(', ')} 中的一个`;
      }
    },
    description: {
      required: false,
      type: 'string',
      maxLength: 200
    },
    permissions: {
      required: false,
      type: 'array'
    }
  });

  if (errors) {
    return res.status(400).json({ message: '输入验证失败', errors });
  }

  // 生成自增id
  currentMaxRoleId++;
  const now = new Date().toISOString();
  const newRole = {
    id: currentMaxRoleId.toString(),
    createdAt: now,
    updatedAt: now,
    permissions: [],
    ...req.body,
  };

  // 添加新角色到数据库
  db.roles.push(newRole);
  updateIndex('roles', newRole, 'add');
  saveDb();

  // 返回新创建的角色
  res.status(201).json(newRole);
});

roleRouter.put('/:id', (req, res) => {
  const roleId = req.params.id;
  const roleIndex = db.roles.findIndex(r => r.id === roleId);

  if (roleIndex === -1) {
    return res.status(404).json({ message: '角色不存在' });
  }

  const oldRole = db.roles[roleIndex];

  // 输入验证
  const errors = validateInput(req.body, {
    name: {
      required: false,
      type: 'string',
      minLength: 1,
      maxLength: 50
    },
    code: {
      required: false,
      type: 'string',
      minLength: 1,
      maxLength: 100
    },
    status: {
      required: false,
      type: 'string',
      validate: (value) => {
        if (!value) return true;
        // 检查状态是否有效
        const validStatuses = ['active', 'inactive'];
        return validStatuses.includes(value) ? true : `状态必须是 ${validStatuses.join(', ')} 中的一个`;
      }
    },
    description: {
      required: false,
      type: 'string',
      maxLength: 200
    },
    permissions: {
      required: false,
      type: 'array'
    }
  });

  if (errors) {
    return res.status(400).json({ message: '输入验证失败', errors });
  }

  const updatedRole = {
    ...oldRole,
    ...req.body,
    updatedAt: new Date().toISOString(),
  };

  // 更新数据库和索引
  db.roles[roleIndex] = updatedRole;
  updateIndex('roles', updatedRole, 'update');
  saveDb();

  res.json(updatedRole);
});

roleRouter.delete('/batch', (req, res) => {
  const { ids } = req.body;
  if (!ids || !Array.isArray(ids)) {
    return res.status(400).json({ message: '请提供有效的角色ID列表' });
  }

  try {
    // 批量删除角色
    const deletedRoles = [];
    for (const id of ids) {
      const roleIndex = db.roles.findIndex(r => r.id === id);
      if (roleIndex !== -1) {
        const deletedRole = db.roles[roleIndex];
        deletedRoles.push(deletedRole);

        db.roles.splice(roleIndex, 1);
        updateIndex('roles', deletedRole, 'delete');
      }
    }

    // 保存数据库
    saveDb();

    res.json(deletedRoles);
  } catch (error) {
    console.error('批量删除角色失败:', error);
    res.status(500).json({ message: '批量删除角色失败' });
  }
});

roleRouter.delete('/:id', (req, res) => {
  const roleId = req.params.id;
  const roleIndex = db.roles.findIndex(r => r.id === roleId);

  if (roleIndex !== -1) {
    const deletedRole = db.roles[roleIndex];
    db.roles.splice(roleIndex, 1);
    updateIndex('roles', deletedRole, 'delete');
    saveDb();
    res.json(deletedRole);
  } else {
    res.status(404).json({ message: '角色不存在' });
  }
});

roleRouter.post('/:id/permissions', (req, res) => {
  const roleId = req.params.id;
  const { permissionIds } = req.body;
  const roleIndex = db.roles.findIndex(r => r.id === roleId);

  if (roleIndex !== -1) {
    const oldRole = db.roles[roleIndex];
    const updatedRole = {
      ...oldRole,
      permissions: permissionIds,
      updatedAt: new Date().toISOString(),
    };

    // 更新数据库和索引
    db.roles[roleIndex] = updatedRole;
    updateIndex('roles', updatedRole, 'update');
    saveDb();

    res.json({ message: '权限分配成功' });
  } else {
    res.status(404).json({ message: '角色不存在' });
  }
});

roleRouter.get('/:id/permissions', (req, res) => {
  const role = indexes.roles.id.get(req.params.id);
  if (role) {
    res.json(role.permissions);
  } else {
    res.status(404).json({ message: '角色不存在' });
  }
});

// 注册路由
app.use('/auth', authRouter);
app.use('/permissions', permissionRouter);
app.use('/users', userRouter);
app.use('/roles', roleRouter);

// 全局错误处理中间件
app.use((err, req, res) => {
  console.error(err.stack);
  res.status(500).json({ message: '服务器内部错误' });
});

// 404中间件
app.use((req, res) => {
  res.status(404).json({ message: '接口不存在' });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`JSON Server 运行在 http://localhost:${PORT}`);
  console.log('API 端点:');
  console.log('  - 认证相关: /auth/*');
  console.log('  - 权限相关: /permissions/*');
  console.log('  - 用户相关: /users/*');
  console.log('  - 角色相关: /roles/*');
  console.log('\n后续添加新模块时，只需创建新的Router并注册到app即可');
});
